<?php

namespace App\Http\Controllers\Manage;

use App\Config;
use App\Rule;
use App\Slide;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Casecate;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Validator;
use App\Cases;

class ConfigController extends Controller
{
    /**
     * @var int 数据表id
     */
    public $table_id = 4;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);

    }

    /**
     * 首页轮播
     */
    public function slide()
    {   $a = 1;
        if(session('id')){
            $a = session('id');
        }
        return view('manage.config.slide',['a'=>$a]);
    }

    public function getSlide()
    {
        $param = Input::get('a');
        $res = Slide::where('id',$param)->first();
        if($res){
            return [
                'code'=>100,
                'res'=>$res
            ];
        }else{
            return [
                'code'=>101,
                'msg'=>'获取失败'
            ];
        }
    }
    public function setSlide()
    {
        $picture = Input::file('picture');
        $url = Input::get('url');
        $id = Input::get('id');
        $rank = Input::get('rank');
        if(empty($id) || empty($url)){
            return back()->withErrors('参数错误！');
        }
        if($picture){
            if($picture->isValid()) {
                $allowed_extensions = ["png", "jpg", "gif"];
                if ($picture->getClientOriginalExtension() && !in_array($picture->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg or gif.'];
                }
                $destinationPath = 'upload/slide/'. date('Y-m-d'); //public 文件夹下面建 productImg/preview/ 文件夹
                $extension = $picture->getClientOriginalExtension();
                $pictureName = '/upload/slide/'.date('Y-m-d') . '/' . str_random(10) . '.' . $extension;
                $picture->move($destinationPath, $pictureName);
                $filePath = asset($destinationPath . $pictureName);
            }else{
                return redirect()->back()->withInput()->withErrors('上传文件有误！');
            }
            $res = Slide::where('id',$id)->update([
                'picture'=> $pictureName,
                'url'=>$url,
                'rank'=>$rank
            ]);
        } else{
            $res = Slide::where('id',$id)->update([
                'url'=>$url,
                'rank'=>$rank
            ]);
        }

        if($res){
            return Redirect::to("manage/config/slide")->with('id',$id);
        }else{
            return redirect()->back()->withInput()->withErrors('添加失败！');
        }
    }
}
